<?php
require "db_api.php";
date_default_timezone_set('Asia/Taipei') ;
while(1) {

	$now=time();
	$tp = date('YmdGi', $now);	//ex:201401021300
	echo "### LOOPING $tp ###\n";
	

	#my $scene= decode_json(read_file("db_scene.json"));
	$allscene = getAllScene();
	foreach($allscene as $key => $scene) {
		$lat = $scene['lat'];
		$lon = $scene['lon'];
		$tbl = $scene['tbl'];
		$try = 0;

		
		 $url     = "http://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon";
again:
		try {
			$weather= json_decode(file_get_contents($url),true);
		} catch (Exception $e) {
			echo "get weather failed. do again after 5s";
			sleep(5);
			$try++;
			if($try < 5)  {
				goto again;
			}
		};
		if(!isset($weather['main']['temp'])) {
			$temperature= 0;
			$weather = "unknown";
		}
		else {
			$temperature= $weather['main']['temp'] - 273;
			$weather = $weather['weather'][0]['main'];
		}
		#echo $weatherTemp."\n";
		#echo $weatherDesc."\n";

		#$json_file="data/".$key.".txt.data".$dayStamp;
		#system("touch $json_file");
		#print $json_file."\n";
		#try {
		#	$tmp = read_file($json_file);
		#	 $decoded = decode_json($tmp);
		#} catch {
		#	undef %decoded;
		#	print "$json_file may be a empty json file\n";
		#};
		#$decoded->{"$hour"."_temp"} =  $weatherTemp;
		#$decoded->{"$hour"."_weather"} =  $weatherDesc;
		#write_file($json_file, encode_json($decoded));
		#$tmp = $key.".txt";
		#system("chmod 777 data/*");
		#system("wget 'http://162.243.140.106/visitors/count_top.php?place=$tmp' -O tmp");
		$url = "http://162.243.140.106/visitors/count_top.php?place=$tbl";
		$webContent = file_get_contents($url);
		echo $scene['cname']." 溫度 $temperature 天氣 $weather $url ==> ".trim($webContent)."\n";
		$checkins = json_decode($webContent,true);
		$totalCheckins = $checkins['checkins'];
		#echo $totalCheckins."\n";
		insert_tbl_record($tbl, $tp, $weather, $temperature, $totalCheckins);
		

		#printf("%s 溫度: %s 天氣: %s\n", $scene->{$key}->{'cname'},  $weatherTemp,  $weatherDesc);

		
	}
	print "ROUND END ################\n";
	sleep(3600);
	}
?>
